package br.org.group.android.gui;


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RemoteViews;
import br.org.group.android.app.ConfigurationVO;
import br.org.group.android.app.FortuneProvider;
import br.org.group.android.app.FortuneVO;
import br.org.group.android.app.R;
import br.org.group.android.dao.FortunesDbAdapter;
import br.org.group.android.utils.FortuneProviderUtils;

public class FortunesWidget extends AppWidgetProvider {

	// actions do widget
	public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
	public static String ACTION_OPEN_ACTIVITY = "ActionActivityOpen";
	public static String FORTUNE_ID = "FortuneID";
	public static String FORTUNE_AUTOR = "FortuneAutor";
	public static String FORTUNE_MSG = "FortuneMSG";
	
	public static boolean useNewTheme = false;
	// classe que implementa a interface provider que fornece as fortunes
	private static FortuneProvider provider;
	private FortuneVO fortune;
	private static RemoteViews views;
	
	
	// ocorre quando o primeiro widget é adicionado
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);

	}

	// Método executado na criação de cada widget
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);

		int N = appWidgetIds.length;

		// Faz um loop para cada App Widget que pertence a esse provider
		for (int i = 0; i < N; i++) {

			int appWidgetId = appWidgetIds[i];

			
			provider = FortuneProviderUtils.getInstance(context);
			fortune = provider.updateFortune();

			updateWidget(context,appWidgetId,fortune);

		}

	}

	@Override
	public void onReceive(Context context, Intent intent) {

		super.onReceive(context, intent);

		// Atualiza a widget clicada com uma nova fortune
		if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
			Bundle extras = intent.getExtras();
			if (extras == null)
				return;

			// Busca o ID do widget nos extras para atualizar apenas o widget
			// clicado
			int widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);

			if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID)
				return;
			int fortuneID = extras.getInt(FORTUNE_ID,0);
			
			provider = FortuneProviderUtils.getInstance(context);
			if(fortuneID > 0){
				fortune = provider.getFortune(fortuneID);
			}else{
				fortune = provider.updateFortune();
			}
			 updateWidget(context,widgetId, fortune);
		}
		
	}

	// método chamado pela activity para atualizar a fortune da widget
	public static void updateWidget(Context context, int appWidgetId, FortuneVO fortune) {

		
		// Atualiza todas as widgets do Froid na área de trabalho
		// Intent para setar a action Receiver e um Extra com o ID do widget
		Intent intentUpdate = new Intent(context, FortunesWidget.class);
		intentUpdate.setAction(ACTION_WIDGET_RECEIVER);
		intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
				appWidgetId);
		 
		PendingIntent actionPendingIntentUpdate = PendingIntent
				.getBroadcast(context, appWidgetId, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT);
		
		views = new RemoteViews(context.getPackageName(),
				R.layout.fortunes_widget);

		views.setOnClickPendingIntent(R.id.ibtn_wid_refresh,
				actionPendingIntentUpdate);
		
		views.setTextViewText(R.id.txt_wid_mensagem,
				getFormatedFortuneMessage(fortune));
		
		ConfigurationVO c = (new FortunesDbAdapter(context)).getConfiguration(ConfigurationVO.CONFIG_ICONS);
			if(c.getValue() == ConfigurationVO.ICONS_NEW){
				useNewTheme = true;
			}else{
				useNewTheme = false;
			}
		
		if(useNewTheme){
			//views.setBitmap(R.id.bgcolor, "setImageBitmap",BitmapFactory.decodeResource(context.getResources(),R.drawable.appwidget_inner_press_l));
			views.setImageViewResource(R.id.bgcolor, R.drawable.appwidget_bg_new);
			views.setTextColor(R.id.txt_wid_mensagem, context.getResources().getColor(android.R.color.black));
		}else{
			views.setImageViewResource(R.id.bgcolor, R.drawable.appwidget_bg);
			views.setTextColor(R.id.txt_wid_mensagem, context.getResources().getColor(android.R.color.white));
		}
		
		Intent intentOpen = new Intent(context, FortunesActivity.class);
		intentOpen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intentOpen.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
				appWidgetId);
		
		//So está pegando esse valor da primeira vez!
		intentOpen.putExtra(FortunesWidget.FORTUNE_ID, fortune.getId());
		intentOpen.putExtra(FortunesWidget.FORTUNE_AUTOR, fortune.getAutor());
		intentOpen.putExtra(FortunesWidget.FORTUNE_MSG, fortune.getMensagem());
		
		PendingIntent actionPendingIntentOpen = PendingIntent.getActivity(
				context, appWidgetId, intentOpen, PendingIntent.FLAG_UPDATE_CURRENT);
		
		views.setOnClickPendingIntent(R.id.txt_wid_mensagem,
				actionPendingIntentOpen);
		views.setOnClickPendingIntent(R.id.txt_appwidget,
				actionPendingIntentOpen);
		
		
		AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId,
				views);

	}

	// atualiza a fortune pelo id e retorna a mensagem
	private static String getFormatedFortuneMessage(FortuneVO fortune) {
		return formatFortune(fortune.getMensagem());
	}

	// formata a fortune limitando em 3 linhas para o widget
	private static String formatFortune(String fortune) {
		String res = "";
		if (fortune != null && fortune.length() > 0) {
			res = fortune.length() > 100 ? fortune.substring(0, 100) + "..."
					: fortune;
		}
		
		return res;
	}

}